<?php

namespace App\Service\authority;
use App\Service\CommicService;
use App\Model\User;
class UserService extends CommicService
{
    public $expire_in;

    public function setUser($access_token,$userInfo){

        $redisKey = 'web_userInfo:'.$access_token;
        $this->redisService->setex($redisKey,14400,json_encode($userInfo));
    }

    public function delUser($access_token){

        $this->redisService->del('web_userInfo:'.$access_token);
    }

    public function getUser($access_token){

      return  $this->redisService->get('web_userInfo:'.$access_token);
    }

    public function generateToken(string $username)
    {
        $this->access_token = md5($username . time() . rand(1000, 9999));
        $this->expire_in = time()+ 14400;
        return [
            'access_token' => $this->access_token,
            'expire_in'    => $this->expire_in,
        ];
    }
    public function checkUser(string $username,string $password){

       $userInfo =  User::query()->where('username',$username)->select('id','username','access_token','password','real_name','roles_ids')
           ->where(['status' => User::STATUS_SHOW])
           ->first();
       if(empty($userInfo)){
           return false;
       }
       $password = md5($password);
       if($userInfo->password != $password){
           return false;
       }

       return $userInfo;
    }


    public function refreshPermissions(string $access_token){

        $userInfo = User::query()->where(['access_token' => $access_token])->select('id','username','access_token','password','real_name','roles_ids')
            ->where(['status' => User::STATUS_SHOW])->first();
        if(empty($userInfo)){
            return false;
        }
        $menuList = $this->getMenuList($userInfo);

        $returnData   = [
            'menuList'    => $menuList['menuList'],
            'permissions' => $menuList['permissions'],
            'user'        => $userInfo,
        ];

        return $returnData;

    }
}